import { h, ref, reactive } from 'vue';
import { definePlugin } from '@/components/@comp/create-component';
import { ElButton } from 'element-plus';
import { Form } from '@/components/@comp/common-form';
import { GridItem } from '@/components/@comp/grid';

// console.log(Form);

export default definePlugin({
  name: 'search',
  priority: 'CONTENT',
  props: { columns: Array, search: { type: Object, default: {} } },
  useMain(instance, props) {
    // console.log(props);
    const { columns, search } = props;

    const initFormValues = {
      ...columns.reduce((store, item) => {
        return (store[item.name || item.dataIndex] = null), store;
      }, {}),
      ...search.defaultValue,
    };

    const form = ref(null);
    const formValue = reactive(initFormValues);

    const { request } = instance.getPlugin('request');

    return {
      head: () => {
        return h(
          Form,
          { form, type: 'search', model: formValue, inline: true, columns, column: 4, gap: '16px', labelWidth: 'auto' },
          {
            default: () =>
              h(GridItem, { colSpan: 1, style: { textAlign: 'right' } }, () => [
                h(ElButton, { onClick: () => form.value.resetFields() }, () => '重置'),
                h(
                  ElButton,
                  {
                    type: 'primary',
                    onClick: async () =>
                      await form.value.validate((valid) => {
                        if (valid) request.search(formValue);
                      }),
                  },
                  () => '查询',
                ),
              ]),
          },
        );
      },
    };
  },
});
